<?php

class MyfirmsController extends UserController {

	public function actionChangeplan($id) {
		$model = $this->loadModel($id, 'Firms');
		if (isset($_POST['Firms']) && $model) {
			if (Yii::app()->user->id == $model->user_id) {
				$new_firm_tmpl = intval($_POST['Firms']['firm_tmpl_id']);
				if ($new_firm_tmpl != $model->firm_tmpl_id) {
					$firmTmpl = FirmTmpls::model()->findbyPk($new_firm_tmpl);
					if ($firmTmpl) {
						$model->firm_tmpl_id = $firmTmpl->id;
						$model->processed = 0;
						$now = time();
						$model->start_date = $now;
						//$model->end_date = $now + $this->getLifeTimeInterval($firmTmpl->trial_time);
						$model->rating_order = intval($firmTmpl->rating_score);
						if ($model->save()) {
							Yii::app()->user->setFlash('user_myfirms_msg', UserModule::t('Пакет услуг изменен успешно.'));
							$this->redirect(array('/user/myfirms/update', 'id'=>$model->id));
						}
					}
				}
			}
		}
//		Yii::app()->user->setFlash('user_myfirms_msg', UserModule::t('Firm data updated sucessfully!'));		
		$this->render('changeplan', array('model' => $model));
	}

	public function actionHidden($id, $hidden) {
		$model = $this->loadModel($id, 'Firms');
		$hidden = intval($hidden);
		$error = null;
		if (!$model) {
			$error = UserModule::t('Такая фирма не найдена');
		} else {
			if (Yii::app()->user->id != $model->user_id) {
				$error = UserModule::t('Чужая фирма');
			} else {
				$model->hidden = $hidden;
				if (!$model->save()) {
					$error = UserModule::t('Проблема с базой');
				}
			}
		}
		
		if (Yii::app()->getRequest()->getIsAjaxRequest()) {
			return $this->ajax_responce($error ? array('error' => $error) : 'success');
			Yii::app()->end();
		} else {
			if (!$model) {
				Yii::app()->user->setFlash('user_myfirms_msg', $error);
				$this->redirect(array('/user/myfirms'));
			} else {
				if ($error) {
					Yii::app()->user->setFlash('user_myfirms_msg', $error);
				} else {
					Yii::app()->user->setFlash('user_myfirms_msg', UserModule::t($hidden ? 'Фирма скрыта' : 'Фирма стала видима'));
				}
				$this->redirect(array('/user/myfirms/update', 'id'=>$model->id));
			}
		}
	}
	

	public function actionCreate() {
		$model = new Firms;
		if (isset($_POST['Firms'])) {
			$model->setAttributes($_POST['Firms']);
      $model->country_id = Yii::app()->params['default_country_id'];
      $firmTmpl = FirmTmpls::model()->findbyPk($model->firm_tmpl_id);
      if ($firmTmpl) {
        $model->active = 1;
        $model->processed = 0;
        $model->admin_status = 0;
        $model->user_status = 1;
        $now = time();
        $model->start_date = $now;
        $enddate = 0;
        if (0 < intval($firmTmpl->trial_time)) {
          $enddate = $this->getLifeTimeInterval($firmTmpl->trial_time);
        }
        $model->end_date = $now + $enddate;
        $model->rating_order = intval($firmTmpl->rating_score);
        $model->author_id = Yii::app()->user->id;	
        $model->user_id = Yii::app()->user->id;
        
        if ($model->save()) {
          if (Yii::app()->getRequest()->getIsAjaxRequest()) {
            Yii::app()->end();
          } else {
            if (0 < $model->id) {
                Yii::app()->user->setFlash('user_myfirms_msg', UserModule::t('Фирма создана успешно. Появилась возможность добавить логотип и фотографии.'));
                $this->redirect(array('/user/myfirms/update', 'id'=>$model->id));
            } else {
                $this->redirect(array('/user/myfirms'));
            }
          } 
        }
      } else {
        Yii::app()->user->setFlash('user_myfirms_msg', UserModule::t('Пакет услуг не выбран'));
      }
		}
		$this->render('create', array( 'model' => $model));
	}

	public function actionUpdate($id) {
		$model = $this->loadModel($id, 'Firms');
    $this->cssFile = $this->getBaseUrl().'/css/swfuploader.css';
		if (isset($_POST['Firms'])) {
      if (isset($_POST['Firms']['logo']) && '' == $_POST['Firms']['logo']) unset($_POST['Firms']['logo']);
			$model->setAttributes($_POST['Firms']);
      $old_img_name = $model->logo;
      $upload_data = $this->uploadFirmImg($model, 'logo');
      $model->logo = $upload_data['img_name'];
      $resize = $upload_data['success'];            
			if ($model->save()) {
				if ($resize) {
          $this->resizeFirmImg($model->logo, array('firms_img_logo' => array('w'=>$this->getYiiP('firms_logo_w'), 'h'=>$this->getYiiP('firms_logo_h'))) );
				}            
        Yii::app()->user->setFlash('user_myfirms_msg', UserModule::t('Информация о фирме сохранена успешно'));
        $this->redirect(array('/user/myfirms/update', 'id'=>$model->id));
			}
		}
    
		$this->render('update', array('model' => $model));
	}
	
	
	public function actionDelete($id) {
    $model = $this->loadModel($id, 'Firms');
		$is_ajax_r = Yii::app()->getRequest()->getIsAjaxRequest();
		
    if (!$model) {
			if ($is_ajax_r) {
				throw new CHttpException(404, UserModule::t('Некорректный запрос.'));    	
			} else {
				Yii::app()->user->setFlash('user_myfirms_msg', UserModule::t('Некорректный запрос.'));
				$this->redirect(array('/user/myfirms/'));
			}
    }
		// $this->deleteLogo($model->logo);
		// $model->delete();
		if (Yii::app()->user->id != $model->author_id) {
			if ($is_ajax_r) {
				throw new CHttpException(404, UserModule::t('Доступ запрещен.'));
			} else {
				Yii::app()->user->setFlash('user_myfirms_msg', UserModule::t('Доступ запрещен.'));
				$this->redirect(array('/user/myfirms/'));
			}
		}
		$model->deleted = 1;
		if ($model->save()) {
			$message = UserModule::t('Фирма удалена успешно');
		} else {
			$message = UserModule::t('Ошибка при удалении');
		}
		if ($is_ajax_r) {
			throw new CHttpException(404, $message);
		} else {
			Yii::app()->user->setFlash('user_myfirms_msg', $message);
			$this->redirect(array('/user/myfirms/'));
		}		
	}    
    
	public function actionDeleteLogo() {
		if (!Yii::app()->getRequest()->getIsAjaxRequest()) $this->redirect(array('/user/myfirms/'));
		$record_id = intval(CHttpRequest::getParam('id'));
		if (0 >= $record_id) $this->ajax_responce('error:record_id');
    $model = $this->loadModel($record_id, 'Firms');
		if (!$this->deleteLogo($model->logo)) $this->ajax_responce('error:deleting');
    $model->logo = '';
    $model->save();
		return $this->ajax_responce('success');
	}
    
	protected function deleteLogo($logo) {
    if ('' == $logo) return false;
    @unlink($this->getFirmImgSrc($logo, 'firms_img_logo', 'real'));
		@unlink($this->getFirmImgSrc($logo, 'firms_img_orig', 'real'));
		return true;
	}     
    
	public function actionIndex() {
		$firms = Firms::model()->with('region', 'city', 'rubric', 'category', 'firmTmpl')->findAll('t.deleted != 1 AND t.author_id = :uid', array('uid' => intval(Yii::app()->user->id)));
		$this->render('index', array(
			'firms' => $firms,
      'default_free_firm_tmpl_ids' => Yii::app()->params['default_free_firm_tmpl_ids']
		));	
	/*
		$dataProvider = new CActiveDataProvider('Firms', array(
			'criteria'=>array(
				'condition'=>'user_id='.intval(Yii::app()->user->id),
				'order'=>'crdate DESC',
				//'with'=>array('author'),
			),
		));
		
		$this->render('index', array(
			'dataProvider' => $dataProvider,
		));
		*/
	}

	public function actionAdmin() {
		return $this->actionIndex();
		/*
		$model = new Firms('search');
		$model->unsetAttributes();

		if (isset($_GET['Firms']))
			$model->setAttributes($_GET['Firms']);

		$this->render('admin', array(
			'model' => $model,
		));
		*/
	}


    public function actionUploadImage($fid) {
        $firm_id = intval($fid);
        if (0 >= $firm_id) {
            echo UserModule::t('Неверный параметр фирмы.'); //$this->ajax_responce('error:record_id');
            Yii::app()->end();
        }
        $firm = Firms::model()->findByPk($fid);
        if (!$firm) {
            echo 'Error: firm not exists;'; //$this->ajax_responce('error:record_id');
            Yii::app()->end();            
        }
        
        $model = new FirmMedia();
        $model->media_type = 1;
        $model->firm_id = $firm_id;
        $model->user_id = Yii::app()->user->id;
        $upload_data = $this->uploadFirmImg($model, 'name', $model->firm_id,'','Filedata');

        if ($upload_data['success']) {
            $model->name = $upload_data['img_name'];
			if ($model->save()) {
                $this->resizeFirmImg($model->name, array(
                        'firms_img_thumb' => array('w'=>$this->getYiiP('firms_thumb_w'), 'h'=>$this->getYiiP('firms_thumb_h')),
                        'firms_img_mid' => array('w'=>$this->getYiiP('firms_mid_w'), 'h'=>$this->getYiiP('firms_mid_h')),
                        'firms_img_big' => array('w'=>$this->getYiiP('firms_big_w'), 'h'=>$this->getYiiP('firms_big_h')),
                    )
                );
                echo "FILEID:" . $this->getFirmImgSrc($model->name, 'firms_img_thumb');              
			} else {
				//Debug::dd($model->getErrors());
				echo 'Model saving error';
			}   
				
        } else {
            echo 'Error: some error;';
        }
        Yii::app()->end();  
    }    

}
?>